import {defineStore} from "pinia";
import MyDayjs from "@/utils/common/myDayjs";
import MyEventSource from "@/utils/common/myEventSource";


//返回值：函数，得到容器示例

export const useAiStore = defineStore('ai', {
    /**
     * 加入插件后 持久化开启
     */
    persist: true,
    /**
     * 全局状态
     * 函数式 在服务端渲染时避免交叉请求导致数据状态污染
     * 箭头函数 方面TS类型推导
     */
    state: () => {
        return {
            userInfo: {} as IUserInfo,
            token: '',
            refreshToken: '',

            eventSource: {} as MyEventSource,
            sessionList: [] as IAiSession[],
            curSession: {} as IAiSession,
            takeMessageNum: 7,
            apiKey: ''
        }
    },
    /**
     * 封装计算属性，有缓存功能
     */
    getters: {
        isLogin(state) {
            return state.userInfo.username && state.userInfo.username !== '' && state.userInfo.username !== undefined
        }
    },
    /**
     * 封装业务逻辑，修改state
     */
    actions: {
        setUserInfo(params: any) {
            this.userInfo = params
        },
        setToken(params: any) {
            this.token = params
        },
        setRefreshToken(params: any) {
            this.refreshToken = params
        },

        newSession() {
            // @ts-ignore
            if (this.sessionList && this.sessionList.length && this.sessionList.at(0).messages.length === 1) {
                this.curSession = this.sessionList.at(0) || {} as IAiSession
                return
            }
            const item: IAiSession = {
                id: MyDayjs().unix(),
                title: '新的会话',
                createdAt: MyDayjs().format('YYYY-MM-DD HH:mm'),
                messages: [
                    {
                        role: 'assistant',
                        content: '有什么可以帮你的吗',
                        createdAt: MyDayjs().format('YYYY-MM-DD HH:mm'),
                    },
                ],
                username: 'username',
                systemHistorySummary: '',
                isReplying: false,
                ctrl: 'new AbortController(),'
            }
            this.sessionList.unshift(item)
            this.curSession = this.sessionList[0]
        },
        sendMessage(content: string) {
            this.curSession.messages.push({
                role: 'user',
                content: content,
                createdAt: MyDayjs().format('YYYY-MM-DD HH:mm'),
            }, {
                role: 'assistant',
                content: '稍等，正在思考中...',
                createdAt: MyDayjs().format('YYYY-MM-DD HH:mm'),
            })
            let lastAiMessageIndex = this.curSession.messages.length - 1
            this.handleCompletions(this.curSession, lastAiMessageIndex)
        },
        stopReply() {
          this.eventSource.close()
        },
        handleCompletions(session: IAiSession, lastAiMessageIndex: number) {
            this.eventSource = new MyEventSource(
                'https://zzjtpp.top/ChatGPT',
                {
                    "messages": this.handleMessageFormat(this.curSession) ,
                    "stream": true,
                    "model": "gpt-3.5-turbo",
                    "temperature": 1,
                    "presence_penalty": 0
                }, {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + 'nk-zzj314314',
                }
            )
            this.eventSource.addEventListener('open', (res: any) => {
                session.messages[lastAiMessageIndex].content = ''
                session.isReplying = true
                console.log('open', res)
            })
            this.eventSource.addEventListener('message', (res: any) => {
                if (res.data !== '[DONE]') {
                    session.messages[lastAiMessageIndex].content += res.data.choices[0].delta.content || ''
                }
            })
            this.eventSource.addEventListener('error', (error: any) => {
                console.error('error', error)
                console.log('error', error.message)
                session.messages[lastAiMessageIndex].content += error.message
            })
            this.eventSource.addEventListener('complete', (res: any) => {
                console.log('complete', res)
                session.isReplying = false
                if ((session.messages.length >= 7 || (session.messages.length >= 3 && JSON.stringify(session.messages).length > 500)) && session.title === '新的会话') {
                    this.handleTitle(session)
                }
                if ((session.messages.length - 1) % (this.takeMessageNum - 1) === 0 && JSON.stringify(session.messages).length > 500) {
                    this.handleSummary(session)
                }
            })


        },

        handleMessageFormat(session: IAiSession) {
            let messages = session.messages.slice(-this.takeMessageNum)
            let messageRes: IAiMessage[] = [{
                role: 'system',
                content: `\n` +
                    'You are ChatGPT, a large language model trained by OpenAI.\n' +
                    'Knowledge cutoff: 2021-09\n' +
                    'Current model: gpt-3.5-turbo\n' +
                    `Current time: ${MyDayjs().format('YYYY-MM-DD HH:mm')}\n`,
            },]
            if (session.systemHistorySummary) {
                messageRes.push({
                    content: session.systemHistorySummary,
                    role: 'system',
                })
            }
            messages.forEach((item) => {
                messageRes.push({
                    content: item.content,
                    role: item.role === 'assistant' ? 'assistant' : 'user',
                })
            })
            return messageRes
        },
        handleTitle(session: IAiSession) {
            let messageRes: IAiMessage[] = []
            session.messages.forEach((item) => {
                messageRes.push({
                    content: item.content,
                    role: item.role === 'assistant' ? 'assistant' : 'user',
                })
            })
            messageRes.push({
                content: '使用四到五个字直接返回这句话的简要主题，不要解释、不要标点、不要语气词、不要多余文本，如果没有主题，请直接返回“闲聊”',
                role: 'user',
            })
            let eventSource= new MyEventSource(
                'https://zzjtpp.top/ChatGPT',
                {
                    "messages": messageRes ,
                    "stream": true,
                    "model": "gpt-3.5-turbo",
                    "temperature": 1,
                    "presence_penalty": 0
                }, {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + 'nk-zzj314314',
                }
            )
            eventSource.addEventListener('open', (res: any) => {
                if(res.statusCode===200){
                    session.title = ''
                }
            })
            eventSource.addEventListener('message', (res: any) => {
                if (res.data !== '[DONE]') {
                    session.title  += res.data.choices[0].delta.content || ''
                }
            })


        },
        handleSummary(session: IAiSession) {
            let messageRes: IAiMessage[] = []
            if (session.systemHistorySummary) {
                messageRes.push({
                    content: session.systemHistorySummary,
                    role: 'system',
                })
            }
            session.messages.slice(-this.takeMessageNum).forEach((item) => {
                messageRes.push({
                    content: item.content,
                    role: item.role === 'assistant' ? 'assistant' : 'user',
                })
            })
            messageRes.push({
                content: '简要总结一下对话内容，用作后续的上下文提示 prompt，控制在 200 字以内',
                role: 'system',
            })
            let eventSource= new MyEventSource(
                'https://zzjtpp.top/ChatGPT',
                {
                    "messages": messageRes ,
                    "stream": true,
                    "model": "gpt-3.5-turbo",
                    "temperature": 1,
                    "presence_penalty": 0
                }, {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + 'nk-zzj314314',
                }
            )
            eventSource.addEventListener('open', (res: any) => {

            })
            eventSource.addEventListener('message', (res: any) => {
                if (res.data !== '[DONE]') {
                    session.systemHistorySummary  += res.data.choices[0].delta.content || ''
                }
            })

        }

    },
})
